from datetime import datetime

from django.shortcuts import render, HttpResponse, redirect

from app01.models import MuseumName
from web.forms.account import *
from django.http import JsonResponse

from io import BytesIO
from utils.image_code import check_code

# 执行复杂查询 使用 & ｜ 时
from django.db.models import Q

from web.models import CollectMuseum, UserInfo


def send_sms(request):
    """
        发送短息
    :param request:
    :return:
    """

    form = SendSmsForm(request, data=request.GET)
    if form.is_valid():
        return JsonResponse({'status': True})
    return JsonResponse({'status': False, 'error': form.errors})


def register(request):
    """
        用户信息注册
    :param request:
    :return:
    """
    if request.method == 'GET':
        form = RegisterModelForm(request)
        return render(request, 'register.html', {'form': form})
    form = RegisterModelForm(request, data=request.POST)
    if form.is_valid():
        # 实现保存功能
        form.save()
        return JsonResponse({'status': True, 'data': '/web/login/'})
    return JsonResponse({'status': False, 'error': form.errors})


def login_sms(request):
    """
     根据手机验证码进行登录
    :param request:
    :return:
    """
    if request.method == 'GET':
        form = loginSmsForm(request)
        return render(request, 'login_sms.html', {'form': form})
    form = loginSmsForm(request, data=request.POST)
    if form.is_valid():
        mobile_phone = form.cleaned_data['mobile_phone']
        # 根据手机号查询用户信息
        user_obj = models.UserInfo.objects.filter(mobile_phone=mobile_phone).first()
        request.session['user_id'] = user_obj.id
        request.session['username'] = user_obj.username
        request.session.set_expiry(60 * 60 * 24 * 14)
        return JsonResponse({'status': True, 'data': '/app01/example/'})
    return JsonResponse({'status': False, 'error': form.errors})


def login(request):
    """
        用户名密码登录功能
    :param request:
    :return:
    """
    if request.method == 'GET':
        form = loginForm(request)
        return render(request, 'login.html', {'form': form})
    form = loginForm(request, data=request.POST)
    if form.is_valid():
        # 要去数据库进行校验
        username = form.cleaned_data['username']
        password = form.cleaned_data['password']
        user_obj = models.UserInfo.objects \
            .filter(Q(email=username) | Q(mobile_phone=username)) \
            .filter(password=password) \
            .first()
        if user_obj:
            request.session['user_id'] = user_obj.id
            request.session['username'] = user_obj.username
            request.session.set_expiry(60 * 60 * 24 * 14)

            return redirect('/app01/example')

        form.add_error('username', '用户名或密码错误')
    return render(request, 'login.html', {'form': form})


def image_code(request):
    """
        生成图片验证码
    :param request:
    :return:
    """
    image_obj, code = check_code()
    # 将图片验证码保存到session中
    request.session['image_code'] = code
    request.session.set_expiry(60)

    stream = BytesIO()
    image_obj.save(stream, 'png')
    stream.getvalue()
    return HttpResponse(stream.getvalue())


def logout(request):
    """
        用户退出
    :param request:
    :return:
    """
    request.session.flush()
    return redirect('/web/login/')


# 删除收藏
def delete_fav(request):
    fav_id = request.GET.get('id')
    print(fav_id)
    return HttpResponse(fav_id)


def user_page(request):
    fmod = CollectMuseum.objects
    umod = UserInfo.objects
    uid = request.session['user_id']  # 获取当前哪个用户登录
    fav_list = fmod.filter(who_clt_id=uid)  # 获取用户的所有收藏
    u = umod.filter(id=uid)[0]
    context = {'favourite_list': fav_list, 'user': u}

    return render(request, 'user_page.html', context)


def collect_museum(request):
    try:
        print('yes')
        sid = request.GET.get('id')  # 前端获取被点击的博物馆name
        uid = request.session['user_id']  # session中提取是哪个用户要保存，即当前登录的用户
        cltm = CollectMuseum()

        # 如果收藏夹里尚未有这个收藏：那就收藏这个条目
        # 如果收藏夹里已经有了，那就取消收藏
        fav_list = CollectMuseum.objects.filter(who_clt_id=uid)  # 找出所有该用户的收藏

        if fav_list.filter(clt_relation_museum_id=sid):  # 检查有没有该小说id
            fav_obj = fav_list.get(clt_relation_museum_id=sid)
            fav_obj.delete()  # 收藏夹里已经有了，取消收藏
            return HttpResponse('♡')
        else:
            cltm.who_clt_id = uid
            cltm.clt_relation_museum_id = sid
            cltm.clt_time = datetime.now()
            cltm.save()  # 收藏夹里尚未有这个收藏：收藏这个条目
            return HttpResponse('♥')
    except Exception as err:
        print('失败,', err)
    return HttpResponse('♡')

def detail(request):
    """前台主页，展示所有的小说条目"""
    museum_temp = MuseumName.objects
    sid = 99

    uid = request.session['user_id']  # session中提取当前登录的用户
    fav_list = CollectMuseum.objects.filter(who_clt_id=uid)  # 找出所有该用户的收藏
    if fav_list.filter(clt_relation_museum_id=sid):  # 检查有没有该小说id
        fs = 1  # 已收藏
    else:
        fs = 0  # 未收藏

    m = museum_temp.get(id=sid)
    context = {'novel_detail': m, 'fav_status': fs}
    return render(request, 'temp.html', context)
